/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */

import UIKit

//MARK: - 封装OAuth相关网络请求接口,对应的控制器LSOAuthViewController
class LSUserAccountViewModel: NSObject {
    
    static let sharedUserAccount: LSUserAccountViewModel = LSUserAccountViewModel()
    
    //用户账号类型
    var userAccount: LSUserAccount? {
        return LSUserAccount.loadUserAccount()
    }
    
    //判断是否登录
    var isLogin: Bool {
        return accessToken != nil
    }
    
    //封装accesstoken,判断逻辑
    var accessToken: String? {
        
        //判断accessToken是否为nil
        guard let token = userAccount?.access_token else {
            return nil
        }
        
        //如果accessToken不为nil,判断accessToken的时间是否过期
        let result = userAccount?.expiresDate?.compare(NSDate())
        //如果是降序表示accessToken没有过期
        if result == NSComparisonResult.OrderedDescending {
            return token
        } else {
            return nil
        }
        
    }
    
    //MARK: - 通过code获取accesstoken
    func reqeustAccessTokenWithCode(code: String, callBack: (isSuccess: Bool)->()) {
        
        LSNetworkTools.sharedTools.reqeustAccessTokenWithCode(code) { (response, error) -> () in
            
            if error != nil {
                print("网络请求失败\(error)")
                callBack(isSuccess: false)
                return
            }
            
            //  代码执行到此网络请求成功
            
            //  判断服务端给的数据是否是一个正确的字典
            guard let dic = response as? [String: AnyObject] else {
                print("不是一个正确的字典格式")
                callBack(isSuccess: false)
                return
            }
            //  代码执行到此,字典没有问题
            let userAccount = LSUserAccount(dic: dic)
            print(userAccount.access_token)
            //  请求用户基本信息
            self.requestUserInfo(userAccount, callBack: callBack)
            
        }
    }
    
    //MARK: - 通过access和uid获取用户信息
    private func requestUserInfo(userAccount: LSUserAccount, callBack: (isSuccess: Bool)->()) {
        
        LSNetworkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
            
            if error != nil {
                print("网络请求错误, \(error)")
                callBack(isSuccess: false)
                return
            }
            
            //代码执行到这,表示网络请求成功
            guard let dic = response as? [String: AnyObject] else {
                print("不是正确的")
                callBack(isSuccess: false)
                return
            }
            
            //代码执行到这,表示字典没问题
            let name = dic["name"]
            let avatar_large = dic["avatar_large"]
            
            userAccount.name = name as? String
            userAccount.avatar_large = avatar_large as? String
            
            print(userAccount)
            
            //表示用户登录成功,保存用户账号的类型
            userAccount.saveUserAccount()
            //执行成功回调的闭包
            callBack(isSuccess: true)
        }
    }
}













